<template>
  <a-card :bordered="false" class="card-area">
    <div class="table-page-search-wrapper">
      <a-form layout="vertical">
        <a-row :gutter="48">
          <a-col :md="8" :sm="12">
            <a-form-item label="单位号">
              <a-input v-model="queryParam.dwh" placeholder=""/>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="12">
            <a-form-item label="单位名称">
              <a-input v-model="queryParam.dwmc" placeholder=""/>
            </a-form-item>
          </a-col>
          <template v-if="advanced">
            <a-col :md="8" :sm="12">
              <a-form-item label="单位简称">
                <a-input v-model="queryParam.dwjc" placeholder=""/>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="12">
              <a-form-item label="单位简拼">
                <a-input v-model="queryParam.dwjp" style="width: 100%"/>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-checkbox @change="checkboxChange($event,'sssfbz')">本年度硕士招生</a-checkbox>
              <a-checkbox @change="checkboxChange($event,'bssfbz')">本年度博士招生</a-checkbox>
            </a-col>
          </template>
          <a-col :md="12" :sm="24">
            <span class="table-page-search-submitButtons" >
              <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
              <a-button type="primary" @click="openAdd">添加</a-button>
              <a-button type="primary" @click="batchDelete">删除</a-button>
              <a-button style="margin-left: 8px" @click="() => queryParam = {}">重置</a-button>
              <a @click="advanced = !advanced" style="margin-left: 8px">
                {{ advanced ? '收起' : '展开' }}
                <a-icon :type="advanced ? 'up' : 'down'"/>
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <college-edit
      ref="collegeEdit"
      :visible.sync="visible"
      :editId.sync="editId"
      :selectMenu.sync="selectMenu"
      :confirmLoading.sync="confirmLoading"
      @cancel="visible = false"
      @create="handleCreate"
    />
    <s-table
      ref="table"
      size="default"
      rowKey="key"
      :columns="columns"
      :data="loadData"
      :alert="options.alert"
      :rowSelection="options.rowSelection">

      <span slot="serial" slot-scope="text, record, index">
        {{ index + 1 }}
      </span>

      <a slot="operation" slot-scope="a,b" @click="openEdit(b)">修改</a>
    </s-table>

  </a-card>
</template>

<script>
import { STable } from '~'
import collegeEdit from './collegeEdit'

export default {
  name: 'TableList',
  components: {
    STable,
    collegeEdit
  },
  data () {
    return {
      // 高级搜索 展开/关闭
      advanced: true,
      visible: false,
      editId: null,
      // 查询参数
      queryParam: {},
      // 表头
      columns: [
        {
          title: '序号',
          scopedSlots: { customRender: 'serial' }
        },
        {
          title: '单位号',
          dataIndex: 'dwh'
        },
        {
          title: '单位名称',
          dataIndex: 'dwmc'
        },
        {
          title: '单位英文名称',
          dataIndex: 'dwywmc'
        },
        {
          title: '单位简称',
          dataIndex: 'dwjc'
        },
        {
          title: '单位英文简称',
          dataIndex: 'dwywjc'
        },
        {
          title: '单位简拼',
          dataIndex: 'dwjp'
        },
        {
          title: '单位地址',
          dataIndex: 'dwdz'
        },
        {
          title: '隶属单位号',
          dataIndex: 'lsdwh'
        },
        {
          title: '单位办',
          dataIndex: 'dwbbmc'
        },
        {
          title: '单位类别',
          dataIndex: 'dwlbmc'
        },
        {
          title: '操作',
          dataIndex: 'operation',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        console.log('loadData.parameter', parameter)
        parameter.pageNum = parameter.pageNo
        let params = Object.assign(this.queryParam, parameter)
        return this.$api.base.collegeList(params).then(res => {
          return {
            data: res.data.rows,
            pageNo: parameter.pageNo,
            pageSize: parameter.pageSize,
            totalPage: Math.ceil(res.data.total / parameter.pageSize),
            totalCount: res.data.total
          }
        })
      },
      selectedRowKeys: [],
      selectedRows: [],

      // custom table alert & rowSelection
      options: {
        alert: { show: true, clear: () => { this.selectedRowKeys = [] } },
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.onSelectChange
        }
      },
      optionAlertShow: true, // 是否显示alert，已选中
      confirmLoading: false,
      selectMenu: {}
    }
  },
  created () {
    this.initSelectMenu()
  },
  methods: {
    initSelectMenu () {
      let allRequest = [
        this.$api.base.dictionaryData('TYPE0034'),
        this.$api.base.dictionaryData('TYPE0035')
      ]
      Promise.all(allRequest).then(res => {
        this.selectMenu = {
          dwbb: res[0].data,
          dwlb: res[1].data
        }
      })
    },
    handleCreate () {
      const form = this.$refs.collegeEdit.form
      form.validateFields(async (err, values) => {
        if (err) {
          return
        }
        if (values.sxrq) {
          values.sxrq = values.sxrq.format('YYYY-MM-DD')
        }
        if (values.jlny) {
          values.jlny = values.jlny.format('YYYY-MM-DD')
        }
        if(!values.sssfbz && !values.bssfbz){
          this.$message.warning('至少要勾选一个本年度招生')
          return
        }
        values.sssfbz = values.sssfbz ? 1 : 0
        values.bssfbz = values.bssfbz ? 1 : 0
        this.confirmLoading = true
        let baseApi = this.editId ? 'collegeUpdate' : 'collegeAdd'
        try {
          let res = await this.$api.base[baseApi](Object.assign({id: this.editId}, values))
          this.$message.success(res.msg)
          this.$refs.table.refresh(false)
          this.confirmLoading = false
          form.resetFields()
          this.visible = false
        } catch (error) {
          this.confirmLoading = false
        }
      })
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    batchDelete () {
      if (!this.selectedRowKeys.length) {
        this.$message.warning('请选择需要删除的院系信息')
        return
      }
      this.$confirm({
        title: '确定删除所选中的院系信息?',
        content: '当您点击确定按钮后，这些记录将会被彻底删除',
        centered: true,
        onOk: () => {
          let collegeIds = []
          this.selectedRows.forEach(college => {
            collegeIds.push(college.id)
          })
          this.$api.base.collegeDelete(collegeIds.join(',')).then(() => {
            this.$message.success('删除成功')
            this.selectedRowKeys = []
            this.selectedRows = []
            this.$refs.table.refresh(false)
            this.$refs.table.clearSelected()
          })
        },
        onCancel: () => {
        }
      })
    },
    openAdd () {
      this.editId = null
      this.visible = true
      this.$refs.collegeEdit.form.resetFields()
    },
    openEdit (college) {
      this.visible = true
      this.$nextTick(() => {
        this.$changeDate(college)
        this.$refs.collegeEdit.form.setFieldsValue(college)
        this.$refs.collegeEdit.form.setFieldsValue({sssfbz: +college.sssfbz === 1, bssfbz: +college.bssfbz === 1})
        this.editId = college.id
      })
    },
    checkboxChange (e, key) {
      this.queryParam[key] = e.target.checked ? 1 : 0
    }
  }
}
</script>
